package eSn.File;

import java.io.*;
import java.util.*;

import eSn.Core.Enu;
import eSn.Core.Str;

/***
 * 文本文件读写器
 * @author Administrator
 *
 */
public class TextFile extends eSnFile {

	public TextFile(String FileName,CharSet cs) {
		super(FileName,cs);
	}
	
	public List<String> LoadtoList() throws Exception{
		if (!super.isRead()) throw new Exception();
		
		List<String> v = new ArrayList<String>();
		FileInputStream fis = new FileInputStream(file);
		
		InputStreamReader isr = new InputStreamReader(fis,charset);
		BufferedReader br = new BufferedReader(isr);
		String s=br.readLine();
		while(s != null){
			if ((int)s.substring(0, 1).toCharArray()[0] == 65279) s = s.substring(1);
		   v.add(s);
		   s = br.readLine();
		}
		br.close();
		return v;
	}
	
	public String getAll() throws Exception{
		List<String> v = LoadtoList();
		return Str.Join(v, "\r\n");
	}
	
	public void Write(String src, Enu WriteType) throws Exception{
		if (!super.isWrite()) throw new Exception();
		
		FileOutputStream fos ;
		if (WriteType == Enu.Append ){
			fos = new FileOutputStream(file,true);
		}else{
			fos = new FileOutputStream(file,false);
		}		
		OutputStreamWriter osw  = new OutputStreamWriter(fos,charset); 
	    osw.write(src);
	    osw.flush(); 
	    osw.close();
	}

	public void Append(String src) throws Exception{
		Write(src,Enu.Append);
	}	
	public void OverWriter(String src) throws Exception{
		Write(src,Enu.Override);
	}

	public void toConsole() throws Exception{
		System.out.print(getAll());
	}
}
